/*
	Handle Start page & settings in Start page
*/

// Global variables use in Book view
var maxItemInStartRow = 9;

var startpageVM = function () {

	// Variables for Start page
	var datacontext = new DataContext(),
	startTitle = getLocalizeText('start'),
	isDisplayStartPage = ko.observable(true),
	list = ko.observableArray([]),
	settingList = ko.observableArray([]),
	currentIndexDrag = 0,
	strViewAll = ko.observable(getLocalizeText('viewAll')),
	isStartPageWorkflow = ko.observable(0),
    currentLeft = 0,
    currentTop = 0,
    currentWidth = 0,
    currentHeight = 0,
    currentImg = '',
	/*
		startInfo store data of Start page:
		+ startModel, include array of startCategoryModel in categories
		+ startCategoryModel, include array of startSummaryModel in summaries
	*/
	startInfo = ko.observable(new StartModel()),	

		/* 
			Get book list for start page:
				+ Get list and update local storage
				+ isServer: FALSE = show list in client (does not update live data)
		*/
		getStartPage = function (isServer) {
			var listStartTemp = ko.observableArray([]);

			setTimeout(function () {
				showLoadingDialog();
				isLoading = true;
			}, 1);
			
			datacontext.startPage.getStartPage({
				results: listStartTemp,
				// Key to store local
				key: 'saveFileStartPage' + model.settingsVM.getLanguageString(),
				isServer: isServer,
				// Execute when local storage is available
                callbackFunc: function () {
                    if (listStartTemp().length > 0){
                        afterGetStartPage(listStartTemp()[0].object);
                    }
					
				}				
			}).done(function () {
                    if (listStartTemp().length > 0){
                        CheckExpireSession(
                            listStartTemp, 
                            false,
                            function() {
                                getStartPage(isServer);
                            }, 
                            function(entityResutl) {
                                // [DONE] Same with callbackFunc		
                                afterGetStartPage(entityResutl);
                            });
                    }
			}).fail(function (e) {
                    CheckExpireSessionErrorCallback(e,
                                                    function(){
                                                    /* session expired */
                                                    getStartPage(isServer);
                                                    },
                                                    function(){
                                                    /* not expire */
                                                    
                                                    });
			});
		},

		afterGetStartPage = function(entity) {
			var coverWidth = 100;
			if (entity != undefined) {	
				startInfo(entity);

				// Initialize scrollbar at start page
				if (myScrollStart != null) {
					myScrollStart.destroy();
					myScrollStart = null;
				} 				
				myScrollStart = new iScroll('wrapper_scrollview_start', {
					hideScrollbar: true,
					hScroll: false
				});

				// Add scrollview in vertical & recaculate with of each category
				for (var i = 0; i < startInfo().categories().length; i++) {
					var startItem = startInfo().categories()[i];
					if (startItem.summaries().length > maxItemInStartRow) {
						/* include view more */
						startItem.sizeofscroll(startItem.summaries().length * coverWidth + 100);
					} else {
						startItem.sizeofscroll(startItem.summaries().length * coverWidth);
					}
					if (isiOS || isBB || isAndroid) {
					    if (startItem.scrollview == null) {
					        startItem.scrollview = new iScroll(startItem.id() + 'wrapper', {
					            hideScrollbar: true,
					            hScrollbar: false
                                                               
					        });
					    } else {
					        startItem.scrollview.refresh();
					    }
					}
				}

				myScrollStart.refresh();							
			}

			isLoading = false;
			hideLoadingDialog();
		},

		// Get list of category
		getStartPageSetting = function () {
			isLoading = true;
			showLoadingDialog();
			var listStartTemp = ko.observableArray([]);
			settingList([]);

			datacontext.startPageSetting.getStartPageSetting({
				results: listStartTemp
			}).done(function () {
				CheckExpireSession(
					listStartTemp, 
					true,
					function() {
						getStartPageSetting();
					}, 
					function() {
                        CheckExpireSession(
                        listStartTemp,
                        false,
                        function() {
                            getStartPageSetting();
                        },
                        function(entityResutl) {
                            settingList(entityResutl());
                            refreshStartSetting();
                            model.isDisplaySettingStartPage(true);
                            stackViews.push(strSettingStart);
                            model.showSettingPopupPage();
                        });
						
					});
			}).fail(function (e) {
                    CheckExpireSessionErrorCallback(e,
                                                    function(){
                                                    /* session expired */
                                                    getStartPageSetting();
                                                    },
                                                    function(){
                                                    /* not expire */
                                                    
                                                    });
			});
		},

		// Post start page settings
		postStartPageSetting = function () {
			var listStartTemp = ko.observableArray([]);
			isLoading = true;
			showLoadingDialog();
			/* make data for post */
			var settingListArray = ko.observableArray([]);
			for (var i = 0; i < settingList().length; i++) {
				var settingItem = settingList()[i];
				var settingItemTemp = {
					"list_id": settingItem.listId(),
					"active": settingItem.active()
				};
				settingListArray.push(settingItemTemp);
			}
			var settingListPost = {
				"list": settingListArray()
			};
			/* end make data for post */
			datacontext.startPageSettingPost.postStartPageSetting({
				results: listStartTemp,
				data: settingListPost
			}).done(function () {
				CheckExpireSession(
					listStartTemp, 
					false,
					function() {
						postStartPageSetting();
					}, 
					function() {						
						getStartPage(true);
						setTimeout(function () {
							model.closeSettingStartPage();
						}, 500);
					});
			}).fail(function (e) {
                    CheckExpireSessionErrorCallback(e,
                                                    function(){
                                                    /* session expired */
                                                    postStartPageSetting();
                                                    },
                                                    function(){
                                                    /* not expire */
                                                    
                                                    });
			});
		},

		// [ENHANCE] Update template data-bind (overviewVM)
		viewStartBook = function (item, e) {
            if (isJqmGhostClick()) {
				return;
			}
			isStartPageWorkflow(1);
			var bookitem = new BookModel();
			bookitem.overView.dataId(item.id());
			model.overviewVM.gotoBookDetail(bookitem, function(callback) {
				viewStartBookbyZoomInAnimation(callback, e, item);
			});
            
		},
        
		viewStartBookbyZoomInAnimation = function (callback, e, item) {
		    var topOffSet = $('#' + item.listId() + 'wrapper').offset().top;
		    var startItem = startItemWithItemId(item.listId());
		    var subScrollPositonX = 0;
		    if (isWP) {
		        subScrollPositonX = $('#' + item.listId() + 'wrapper').offset().left;
		    }
		    else {
		        subScrollPositonX = startItem.scrollview.x;
		    }
            var animationDurion = 1000;
            var widthOfScreen = window.innerWidth;
            var	heightOfScreen = window.innerHeight;
            if (isiOS){
            	/* is iOS, animation smooth than other, so it set time to smaller */
            	animationDurion = 500;
            }
            var pos = $(e.target).position(),
                x = pos.left,
                y = pos.top + 44,
                zoom = $('#zoomItem'),
                cover = $('#coverItem'),
                img = $(e.target).attr('src');
            cover.css('left', x + subScrollPositonX + 'px');
            cover.css('top', topOffSet + 8 + 'px');
            cover.css('width', '80px');
            cover.css('height', '120px');
            $($('img', cover)[0]).attr('src', img);
            $('.coverItem img').css('width', '80px');
            $('.coverItem img').css('height', '120px');

            zoom.css('width', '80px');
            zoom.css('height', '120px');
            zoom.css('left', x + subScrollPositonX + 'px');
            zoom.css('top', topOffSet + 8 + 'px');
            /* keep cover position */
            currentLeft = x + subScrollPositonX;
            currentTop = topOffSet + 8;
            currentWidth = 70;
            currentHeight = 110;
            currentImg = $(e.target).attr('src');
            zoom.show();
            cover.show();
            setTimeout(function(){
                       zoom.animate({
                                    top: '44px',
                                    left: '0px',
                                    width: widthOfScreen + 'px',
                                    height: heightOfScreen - 52 - 44 + 'px'
                                    }, animationDurion, function () {
                                        callback();
                                        zoom.hide();
                                    });}, 100);
            setTimeout(function(){
                       cover.animate({
                                    top: '59px',
                                    left: '15px',
                                     width: '92px',
                                     height: '138px'
                                    }, animationDurion, function () {
                                    cover.hide();
                                    });}, 100);
            setTimeout(function(){
                       $('img', cover).animate({
                                    width: '92px',
                                    height: '138px'
                                    }, animationDurion, function () {
                                    
                                    });}, 100);
            
        },
        viewStartBookbyZoomOutAnimation = function(callback) {
            var detailImageOffset = $('#detail-image').offset();
            var animationDurion = 1000;
            var widthOfScreen = window.innerWidth;
            var	heightOfScreen = window.innerHeight;
            
            if (isiOS){
            	/* is iOS, animation smooth than other, so it set time to smaller */
            	animationDurion = 500;
            }
            var zoom = $('#zoomItem'),
            cover = $('#coverItem');
            
            cover.css('left', detailImageOffset.left + 'px');
            cover.css('top', detailImageOffset.top + 'px');
            cover.css('width', '92px');
            cover.css('height', '138px');
            
            $($('img', cover)[0]).attr('src', currentImg);
            
            $('.coverItem img').css('width', '92px');
            $('.coverItem img').css('height', '138px');
            
            zoom.css('width', widthOfScreen + 'px');
            zoom.css('height', heightOfScreen - 52 - 44 + 'px');
            zoom.css('left', '0px');
            zoom.css('top', '44px');
            
            zoom.show();
            cover.show();
            callback()
            
            setTimeout(function(){
                       zoom.animate({
                                    top: currentTop + 'px',
                                    left: currentLeft + 'px',
                                    width: '80px',
                                    height: '120px'
                                    }, animationDurion, function () {
                                    zoom.hide();
                                    });}, 100);
            setTimeout(function(){
                       cover.animate({
                                     top: currentTop + 'px',
                                     left: currentLeft + 'px',
                                     width: '80px',
                                     height: '120px'
                                     }, animationDurion, function () {
                                        cover.hide();
                                     });}, 100);
            setTimeout(function(){
                       $('img', cover).animate({
                                               width: '80px',
                                               height: '120px'
                                               }, animationDurion, function () {
                                               
                                               });}, 100);
            
        },
    
		// [ENHANCE] Move from vm.js
		viewAll = function (item) {
		    model.viewNewestStartPage(0, item);
		},

		// Handle drag item in setting page: change index and status of category
		refreshStartSetting = function () {
			$("#sortable").sortable({
				handle: ".drag-item",
				stop: function (event, ui) {
					if (ui.item.index() != currentIndexDrag) {
						/* swap and caculator list */
						var settingListTemp = ko.observableArray([]);
						var startItem = settingList()[currentIndexDrag];
						var currentIndex = 0;
						for (var i = 0; i < settingList().length; i++) {
							var itemTemp = settingList()[i];
							if (i == ui.item.index()) {
								/* input item start here */
								if (currentIndexDrag > ui.item.index()) {
									/* bring item up */
									startItem.active(itemTemp.active());
									startItem.index(currentIndex++);
									settingListTemp.push(startItem);
									itemTemp.index(currentIndex++);
									settingListTemp.push(itemTemp);
								} else {
									/* bring item down */
									itemTemp.index(currentIndex++);
									settingListTemp.push(itemTemp);
									startItem.active(itemTemp.active());
									startItem.index(currentIndex++);
									settingListTemp.push(startItem);
								}
							} else if (i != currentIndexDrag) {
								/* push item to list is normal */
								itemTemp.index(currentIndex++);
								settingListTemp.push(itemTemp);
							}
						}
						settingList([]);
						settingList(settingListTemp());
					}
				},
				start: function (event, ui) {
					currentIndexDrag = ui.item.index();
				}
			});
			$("#sortable").disableSelection();
			$("#sortable").bind("sortstop", function (event, ui) {
				$('#sortable').listview('refresh');
			});
		},

		// Handle Remove/Add category in setting popup
		deleteItem = function (item) {
			addOrDeleteItem(item, false);
		},

		// [DONE] Merge to deleteItem
		addItem = function (item) {
			addOrDeleteItem(item, true);
		},

		addOrDeleteItem = function(item, active) {
			var itemIndex = item.index();
			item.active(active);
			var settingListTemp = ko.observableArray([]);
			var flag = false;
			var currentIndex = 0;
			for (var i = 0; i < settingList().length; i++) {
				var itemTemp = settingList()[i];
				if (i != itemIndex) {
					if (flag == false && itemTemp.active() == false) {
						flag = true;
						item.index(currentIndex++);
						settingListTemp.push(item);
					}
					itemTemp.index(currentIndex++);
					settingListTemp.push(itemTemp);
				}
			}
			if (flag == false) {
				item.index(currentIndex++);
				settingListTemp.push(item);
			}
			settingList(settingListTemp());
		},
		
		// [Android, Window Phone, BlackBerry] 
		reloadLanguage = function () {
			strViewAll(getLocalizeText('viewAll'));
		},
	    startItemWithItemId = function(strItemId)
        {
            for (var i = 0; i < startInfo().categories().length; i++) {
                var startItem = startInfo().categories()[i];
                if (startItem.id() == strItemId)
                {
                    return startItem;
                }
                
            }
            return null;
	    };

	return {
		startTitle: startTitle,
		strViewAll: strViewAll,
		isStartPageWorkflow: isStartPageWorkflow,
		startInfo: startInfo,
		getStartPage: getStartPage,
		isDisplayStartPage: isDisplayStartPage,
		getStartPageSetting: getStartPageSetting,
		postStartPageSetting: postStartPageSetting,
		viewStartBook: viewStartBook,
		viewAll: viewAll,
		list: list,
		settingList: settingList,
		deleteItem: deleteItem,
		addItem: addItem,
		reloadLanguage: reloadLanguage,
        viewStartBookbyZoomOutAnimation: viewStartBookbyZoomOutAnimation,
	};
}()
